package com.itheima.filter;

import com.alibaba.fastjson2.JSON;
import com.itheima.utils.Result;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: 放学后海堤日记
 * @Date: 2023/4/10 15:39
 * @Desc:
 */
//@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //判断是不是登录请求，是则直接放行请求
        if (request.getRequestURI().toString().contains("/login")) {
            filterChain.doFilter(request, response);
            return;
        }

        //获取请求头里token携带的jwt令牌信息
        String jwt = request.getHeader("token");
        //判断令牌是否存在，不存在则向浏览器响应未登录的响应信息
        if (!StringUtils.hasLength(jwt)) {
            response.getWriter().write(JSON.toJSONString(Result.error("NOT_LOGIN")));
            return;
        }

        //解析令牌
        try {
            Jwts.parser()
                    .setSigningKey("itheima")
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
            //出现异常，说明jwt令牌无效，那么向浏览器响应未登录信息
            response.getWriter().write(JSON.toJSONString(Result.error("NOT_LOGIN")));
            return;
        }

        //令牌正确，放行请求
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
